/**
 * Copyright (C) 2007 Mustafa K. Isik - isik@acm.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

package com.paxcodi.threads.diner.gathering;

public class Philosopher implements Runnable{

	private Seat seat;
	private int meditationTimeInMs;

	/**
	 * Initializes philosopher to be thinking, i.e. neither sitting nor eating.
	 * 
	 * @param seatNumber index of chair on which philosopher is seated - 
	 * required in order to derive relevant chopsticks
	 */
	Philosopher(int meditationTimeInMs) {
		seat = null;
		this.meditationTimeInMs = meditationTimeInMs;
	}

	public void run() {
		while(true){

			sitDown();

			pickUpChopsticks();

			eat(meditationTimeInMs / 2);

			putDownChopsticks();

			getUp();

			meditate(meditationTimeInMs);
		}
	}

	private void sitDown(){
		//note-to-self: need to be seated in order to compete for 
		//chopsticks and eat eventually - the table 
		//can make this philosopher wait()
		seat = CircularTable.getInstance().requestToBeSeated();
	}

	private void pickUpChopsticks(){
		CircularTable.getInstance().requestChopsticksForSeat(seat.getSeatIndex());
	}

	private void eat(final int milliseconds) {
		try {
			System.out.println("P " + Thread.currentThread().getName() + 
					" is eating for " + milliseconds + "ms.\n");
			//chew, swallow and start digesting current bite :)
			Thread.sleep(milliseconds);
		} catch (InterruptedException e) {
			System.err.println("Interrupted while eating ...: " + 
					Thread.currentThread().getName());
		}
	}

	private void putDownChopsticks(){
		//release lock on chopsticks upon finishing this bite
		CircularTable.getInstance().releaseChopsticksForSeat(seat.getSeatIndex());
	}

	private void meditate(final int milliseconds) {
		try {
			System.out.println("P " + Thread.currentThread().getName() + 
					" is meditating for " + milliseconds + "ms.\n");
			Thread.sleep(milliseconds);
		} catch (InterruptedException e) {
			System.err.println("Interrupted during mediatation ...: " + 
					Thread.currentThread().getName());
		}
	}

	private void getUp() {
		CircularTable.getInstance().releaseSeat(seat);
		seat = null; //this is actually not necessary, more of a safety measure
	}


}
